<?php
namespace juhe;
use org\Http;

class juhe
{

    static function ipNew($ip){
        //先查询laysns数据库
        $ipArr=explode(".",$ip);
        if(count($ipArr)!=4){
            return [
                'code' => 0,
                'msg' => 'IP地址不正确',
                'data' => []
            ];
        }

        $updateKey=env('key');
        $res=static::getIpData($ip,$updateKey);
        if(is_array($res)&&$res['code']==1){
            return $res;
        }else {
            $key=sysconfig('juhe.ip_key');
            $ret = Http::get("http://apis.juhe.cn/ip/ipNew?ip={$ip}&key={$key}");
            $res = json_decode($ret, true);
            if ($res['error_code'] == 0) {
                $res['result']['ip'] = $ip;
                static::postIpData($res['result'], $key);
                return [
                    'code' => 1,
                    'msg' => '成功',
                    'data' => $res['result']
                ];
            } else {
                return [
                    'code' => 0,
                    'msg' => $res['reason'],
                    'data' => []
                ];
            }
        }
    }

    static function getIpData($ip,$UpdateKey){
        $res=Http::get("http://api.laysns.com/ip?ip={$ip}&UpdateKey={$UpdateKey}");

        return json_decode($res,true);

    }

    static function postIpData($data,$UpdateKey){
        Http::post("https://api.laysns.com/upd_ip?UpdateKey={$UpdateKey}",$data);
    }
}